let OSS = require('ali-oss')
var fs = require('fs')
const config = require('../../config/config')['aliyun']
const uuid = require('node-uuid')


let client = new OSS({
    region: 'oss-cn-beijing',
    accessKeyId: config.accessKeyId,
    accessKeySecret: config.accessKeySecret,
})

client.useBucket('99send')

module.exports = {

    async putImg(file) {

        const stream = fs.createReadStream(file.path)

        let uid = uuid.v4()

        let lastIndex = file.name.lastIndexOf('.')

        let suffix = file.name.substring(lastIndex, file.name.length)

        let result = await client.put('99send/' + uid + suffix, stream, { headers: { 'content-disposition': 'inline', "content-type": file.type } })
        if (result.res.status === 200) {
            let ossPath = config.ossUrl + result.name
            return { name: result.name, path: result.url, ossPath }
        } else {
            return {}
        }
    },

    async putImgStream(stream, suffix = 'png') {

        let uid = uuid.v4()
        let result = await client.put('99send/' + uid + '.' + suffix, stream, { headers: { 'content-disposition': 'inline', "content-type": `image/${suffix}` } })
        if (result.res.status === 200) {
            let ossPath = config.ossUrl + result.name
            return { name: result.name, path: result.url, ossPath }
        } else {
            return {}
        }
    },
}